package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Member;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.HealthStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * @author wgq
 * @date 2019-10-21 10:21
 * 用户服务 业务层
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    /**
     * 查询登陆账户 --> 管理员
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        if(currentPage == null || currentPage <= 0){
            currentPage = 1;
        }
        Integer pageSize = queryPageBean.getPageSize();
        if(pageSize == null || pageSize <=0){
            pageSize = 10;
        }
        String queryString = queryPageBean.getQueryString();
        if(HealthStringUtils.isEmpty(queryString)){
            queryString="";
        }else{
            queryString = queryString.trim();
        }
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.selectByCondition("%"+queryString+"%");
        long total = page.getTotal();
        List<User> result = page.getResult();
        //SELECT * FROM t_checkitem LIMIT 1,10
        return new PageResult(total, result);
    }


    /**
     * 用户管理：新增用户数据
     * @param user
     * @param roleIds
     */
    @Override
    public void addUser(User user, Integer[] roleIds) {
        if(userDao.findCountByname(user.getUsername())>0){
            throw new RuntimeException("用户名称已存在");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.addUser(user);
        setUserAndRole(user.getId(), roleIds);
    }

    /**
     * 编辑窗口弹出，根据行 ID 回显数据
     * @param id
     * @return
     */
    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    /**
     * 查询用户和角色之间的  对应关系
     * @param id
     * @return
     */
    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    /**
     * 编辑用户
     * @param user
     * @param roleIds
     */
    @Override
    public void edit(User user, Integer[] roleIds) {
        // 根据用户id删除中间表数据（清理原有关联关系）
        userDao.deleteRoleIds(user.getId());
        //向中间表插入数据（建立用户和角色关联关系）
        setUserAndRole(user.getId(),roleIds);
        //更新用户信息
        userDao.edit(user);
    }

    /**
     * 设置用户和角色之间的关系
     * @param userId
     * @param roleIds
     */
    private void setUserAndRole(Integer userId, Integer[] roleIds) {
        if(roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                userDao.setUserAndRole(userId,roleId);
            }
        }
    }
}
